<?php
namespace App\Console\Commands\OverSeasBa;

use App\Models\OverSeasBa\InventoryBox;
use App\Models\OverSeasBa\InventoryBoxFNSku;
use Illuminate\Console\Command;
class SyncBoxFnSku extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'os-ba:sync-box-fnsku';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'exe func';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $items = InventoryBox::query()
            ->selectRaw('account_id,warehouse_id,fnsku,sum((storage_total - out_total) * num_per_box) as instant')
            ->groupBy(['account_id','warehouse_id','fnsku'])
            ->get();
        $path = InventoryBoxFNSku::getFile();
        $fp = fopen($path, 'a');
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($fp, ['类型','账号ID','仓库ID','FNSKU','更新前','更新后']);
        $i = 0;
        $num = 800;
        while(true) {
            if($items->isEmpty())break;
            $_items = $items->splice($i,$num);
            foreach ($_items as $item){
                $re = InventoryBoxFNSku::query()
                    ->where('account_id',$item->account_id)
                    ->where('warehouse_id',$item->warehouse_id)
                    ->where('fnsku',$item->fnsku)
                    ->first();
                if($re){
                    if($re->instant != $item->instant){
                        $old = $re->instant;
                        $re->instant = $item->instant;
                        $re->save();
                        fputcsv($fp, ['up',$item->account_id,$item->warehouse_id,$item->fnsku,$old,$item->instant]);
                    }
                }else{
                    $pSkuId = InventoryBox::query()
                        ->where('account_id',$item->account_id)
                        ->where('warehouse_id',$item->warehouse_id)
                        ->where('fnsku',$item->fnsku)
                        ->value('psku_id');
                    InventoryBoxFNSku::query()->create([
                        'account_id' => $item->account_id,
                        'warehouse_id' => $item->warehouse_id,
                        'fnsku' => $item->fnsku,
                        'psku_id' => $pSkuId,
                        'instant' => $item->instant,
                    ]);
                    fputcsv($fp, ['add',$item->account_id,$item->warehouse_id,$item->fnsku,0,$item->instant]);
                }
            }
        }
        fclose($fp);
        $this->info('finish!');
    }
}
